<?php
# http://projects:8081/cdapp-2kt-api/api/seat_status_tma_set_planning.php
include_once '_portal.php';

if (isset($_GET['clear'])) {
  if ($_GET['clear'] == 'yes') {
    $sql = "UPDATE `2kt_seat_status` SET `planningSectorCodes`= null, `planningFrequency`= null";
    $result = exec_sql($sql);
    output(['result' => $result, 'sql' => $sql]);
  }
} elseif (
  isset($_GET['cover']) &&
  $_GET['cover'] == 'yes' &&
  $post &&
  count($post) > 0
) {
  // clear
  $sql_clear = "UPDATE `2kt_seat_status` SET `planningSectorCodes`= null, `planningFrequency`= null";
  $result_clear = exec_sql($sql_clear);
  // update
  $sql_update = [];
  foreach ($post as $plan) {
    if (gettype($plan->value) == 'array' || gettype($plan->value) == 'object') {
      sort($plan->value);
      $plan->value = json_stringify($plan->value);
    }
    $sql = "UPDATE `2kt_seat_status` SET `{$plan->item}`='{$plan->value}' WHERE `seatName`='{$plan->seat}'";
    $sql_update[] = $sql;
  }
  $result_update = exec_sql_array($sql_update);
  // ueser
  $users = [
    [
      'userId' => 0,
      'seatPost' => '管制岗',
      'seatRole' => '管制',
      'userName' => '(^･ｪ･^)',
      'startTime' => '2023-07-11 09:18:43',
      'seatPostId' => 1,
      'seatRoleId' => 2,
      'controlLevel' => '五级',
      'qualification' => '全放单',
      'controlLevelId' => 5,
      'qualificationId' => 1,
    ],
    [
      'userId' => 0,
      'seatPost' => '协调岗',
      'seatRole' => '管制',
      'userName' => '(๑˘ ˘๑)',
      'startTime' => '2023-07-11 09:11:04',
      'seatPostId' => 2,
      'seatRoleId' => 2,
      'controlLevel' => '五级',
      'qualification' => '全放单',
      'controlLevelId' => 5,
      'qualificationId' => 1,
    ],
  ];
  $users_json = json_stringify($users);
  $sql_user = [];
  $sql_user[] = "UPDATE `2kt_seat_status` SET `users`='{$users_json}' WHERE  JSON_LENGTH(sectorCodes, '$') > 0";
  $sql_user[] = "UPDATE `2kt_seat_status` SET `users`='[]' WHERE JSON_LENGTH(sectorCodes, '$') = 0";
  $result_user = exec_sql_array($sql_user);
  // output
  output([
    'result_clear' => $result_clear,
    'sql_clear' => $sql_clear,
    'result_update' => $result_update,
    'sql_update' => $sql_update,
    'result_user' => $result_update,
    'sql_user' => $sql_user,
  ]);
} elseif ($post && count($post) > 0) {
  $sql_arr = [];
  foreach ($post as $plan) {
    if (gettype($plan->value) == 'array' || gettype($plan->value) == 'object') {
      sort($plan->value);
      $plan->value = json_stringify($plan->value);
    }
    $sql = "UPDATE `2kt_seat_status` SET `{$plan->item}`='{$plan->value}' WHERE `seatName`='{$plan->seat}'";
    $sql_arr[] = $sql;
  }
  $result = exec_sql_array($sql_arr);
  output(['result' => $result, 'sql' => $sql_arr]);
} else {
  output(['result' => '???']);
}
